package cn.dianhun.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author cyt
 * @create 2020-07-17 10:27
 * @EnableGlobalMethodSecurity(securedEnabled = true)
 */
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 配置用户的服务信息
     *        //  manager.createUser(User.withUsername("cyt").password("$2a$10$I9pgiXNbkct5cPlhHMvXfe4J7xk1akU6mIWArNTTAihvHUn1jSkpK").authorities("vip").build());
     *         // manager.createUser(User.withUsername("ccc").password("$2a$10$I9pgiXNbkct5cPlhHMvXfe4J7xk1akU6mIWArNTTAihvHUn1jSkpK").authorities("v").build());
     * @return
     */

/*  @Override
    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();

        return manager;
    }*/

    /**
     * 配置密码的规则
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    String[] SWAGGER_WHITELIST = {
            "/swagger-ui.html",
            "/swagger-ui/*",
            "/swagger-resources/**",
            "/v2/api-docs",
            "/v3/api-docs",
            "/webjars/**"
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()//开启登录配置
                .antMatchers(SWAGGER_WHITELIST).permitAll()
                /**
                 * 表示访问 /test 这个接口，需要具备 vip1 这个角色
                 */
                .antMatchers("/test").hasAnyAuthority("vip1")
                .antMatchers("/cyt").hasAnyAuthority("vip2")
                .antMatchers("/cyt/test").hasAnyAuthority("vip3")
                /**
                 * 表示剩余的其他接口，随便访问
                 */
                .anyRequest().permitAll()
                .and()
                /**
                 * 登陆表单
                 */
                .formLogin()
                /**
                 *  成功后的路由跳转
                 */
                .successForwardUrl("/success");
    }
}
